import { reqAddOrUpdateCart, reqGoodsDetail } from "@/api";

const state = {
  //存储商品详情的数据
  skuInfo: {},
};
const mutations = {
  GETGOODDETAIL(state, skuInfo) {
    state.skuInfo = skuInfo;
  },
};
const actions = {
  async getGoodDetail({ commit, state, dispatch, getters }, skuId) {
    let result = await reqGoodsDetail(skuId);
    if (result.code == 200) {
      commit("GETGOODDETAIL", result.data);
    }
  }, //addOrUpdateCart函数的声明部分,次函数前面+async,次函数返回的一定是Promise对象
  //Promise对象到底是pending|成功|失败|取决于次函数返回的结果
  async addOrUpdateCart(
    { commit, state, dispatch, getters },
    { skuId, skuNum }
  ) {
    //由于此接口data没有人会任何的数据,因此不需要仓库存储数据
    let result = await reqAddOrUpdateCart(skuId, skuNum);
    if (result.code == 200) {
      return "ok";
    } else {
      //加入购物车失败,当前 addOrUpdateCart返回一个失败的Promise对象
      return Promise.reject(new Error(result.message));
    }
  },
};
const getters = {
  //利用小仓库数据:专门把面包屑的数据计算出来
  categoryView(state) {
    // console.log(state);
    //第一次计算:state.skuInfo=>{},空对象.categoryView ->组件接收到的还是undefined
    //第二次计算:state.skuInfo.categoryView->才是组件想要来自于服务器的数据
    return state.skuInfo.categoryView || {};
  },
  //商品信息
  goodsInfo(state) {
    return state.skuInfo.skuInfo || {};
  },
  //商品图片的数据
  skuImageList(state) {
    return (state.skuInfo.skuInfo || {}).skuImageList || [];
  },
  spuSaleAttrList(state) {
    return state.skuInfo.spuSaleAttrList || [];
  },
};
export default {
  state,
  mutations,
  actions,
  getters,
};
